package com.example.mplayer.data

import androidx.room.Dao
import androidx.room.Embedded
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Relation
import androidx.room.Transaction
import kotlinx.coroutines.flow.Flow

@Dao
interface CourseDao {
    @Transaction
    @Query("SELECT * FROM courses")
    fun getAllCourses(): Flow<List<CourseWithChapters>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCourse(course: Course)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertChapters(chapters: List<Chapter>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertVideos(videos: List<Video>)

    @Transaction
    suspend fun insertFullCourse(course: Course, chapters: List<Chapter>, videos: List<Video>) {
        insertCourse(course)
        insertChapters(chapters)
        insertVideos(videos)
    }

    @Query("""
        SELECT * FROM chapters 
        WHERE parentId = :parentChapterId
    """)
    @Transaction
    suspend fun getSubChapters(parentChapterId: String?): List<ChapterWithVideos>

    @Query("SELECT * FROM chapters WHERE id = :chapterId")
    @Transaction
    suspend fun getChapterWithVideos(chapterId: String): ChapterWithVideos

    @Query("""
        SELECT * FROM chapters 
        WHERE courseId = :courseId 
        AND (parentId IS NULL OR parentId = '' OR parentId = '000000000000000000000000')
    """)
    @Transaction
    suspend fun getRootChapters(courseId: String): List<ChapterWithVideos>

    @Query("SELECT * FROM courses WHERE id = :courseId")
    suspend fun getCourseById(courseId: String): Course?
}

data class CourseWithChapters(
    @Embedded val course: Course,
    @Relation(
        entity = Chapter::class,
        parentColumn = "id",
        entityColumn = "courseId"
    )
    val chapters: List<ChapterWithVideos>
)

data class ChapterWithVideos(
    @Embedded val chapter: Chapter,
    @Relation(
        parentColumn = "id",
        entityColumn = "chapterId"
    )
    val videos: List<Video>
) 